import { login, logOut, getInfo } from '@/api/user'
import { resetRouter  } from '@/router'
import router from '@/router'
import {syncRoutes,staticRoutes, everyRoutes} from '@/router/routes'
import {cloneDeep} from 'lodash'
import { Message } from 'element-ui'

// 遍历，筛选出当前用户注册的路由
// syncRoutes:动态路由
// routesName：当前用户注册的路由
function filterRoutes(syncRoutes,routesName){

    return syncRoutes.filter(item => {
   
      if(routesName.includes(item.name)){
        // 说明动态路由中有当前注册的路由

          // 遍历下一层children
          // item.children有可能是undefined，所以这个条件要写到前面
          // 如果前面写item.children.length,而item.children是undefined，那么就会直接报错
          if(item.children && item.children.length > 0){
            return item.children = filterRoutes(item.children,routesName)
          }
        return item
      }
    })
}


const getDefaultState = () => {
  return {
    token: localStorage.getItem('token_key') || '',
    name: '',
    avatar: '',
    buttons: [],
    routes: staticRoutes,
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_BUTTONS(state,buttons){
    state.buttons = buttons
  },
  SET_ROUTES(state,routes){
    state.routes = routes
  }
}

const actions = {

  // 用户登录
  login({ commit,state }, userInfo) {
    return new Promise(async (resolve, reject) => {
      try {
        const result = await login(userInfo)

        commit('SET_TOKEN', result.data.token)
        localStorage.setItem('token_key', result.data.token)
        resolve()
      } catch (error) {
        reject(error)
      }
    })
  },

  // 获取用户信息
  getInfo({ commit }) {
    return new Promise(async (resolve, reject) => {
      try {
        const result = await getInfo()

        if (result.code === 20000) {
          commit('SET_NAME', result.data.name)
          commit('SET_AVATAR', result.data.avatar)
          commit('SET_BUTTONS',result.data.buttons)


          // 根据用户筛选路由
          let routesName = filterRoutes(cloneDeep(syncRoutes),result.data.routes)
          routesName.push(everyRoutes)
          
          router.addRoutes(routesName)
          commit('SET_ROUTES',[].concat(staticRoutes,routesName))

          return resolve()
        } else {
          return reject('获取用户信息失败')
        }
      } catch (error) {
        return reject('请求获取用户信息失败')
      }

    })
  },

  // user logout
  logout({commit,dispatch}) {
    return new Promise(async (resolve, reject) => {
      try {
        await logOut();
        // must remove  token  first
        dispatch('resetToken')
        resolve()
        Message.success("退出成功")
      } catch (error) {
        reject();
        Message.error('退出失败')
      }
    })
  },

  // remove token
  resetToken({commit}) {
    resetRouter();

    localStorage.removeItem('token_key')
    commit('RESET_STATE')
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

